package realtime.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisURI;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.async.RedisAsyncCommands;

/**
 * @Create 2023/9/8 15:43
 */
public class RedisUtil {
    //-------获取获取一个到redis线程安全的异步连接,key value 都用utf-8进行编码
    public static StatefulRedisConnection<String,String> getAsyncRedisConnection(){
        //连接到redis的4号库
        //"redis://hadoop101:6379/4"
        RedisURI redisURI = new RedisURI();
        redisURI.setHost("thadoop102");
        redisURI.setPort(6379);
        redisURI.setDatabase(4);

        RedisClient redisClient= RedisClient.create("redis://@localhost:16379/4");
        return redisClient.connect();
    }

    //关闭异步redis链接
    public static void closeAsyncRedisConn(StatefulRedisConnection<String,String> redisConn){
        if (redisConn != null) {
            System.out.println("~~~关闭异步redis链接~~~");
            redisConn.close();
        }
    }

    //异步链接读取缓存
    public static JSONObject asyncGetDimInfo(StatefulRedisConnection<String,String> redisConn, String key){
        RedisAsyncCommands<String, String> async = redisConn.async();
        try {
            String json = async.get(key).get();
            if (json != null) {
                return JSON.parseObject(json);
            }

        }catch (Exception e){
            throw new RuntimeException();
        }
        return null;
    }

    //异步写入缓存
    public static void asyncSetDimInfo(StatefulRedisConnection<String,String> redisConn,String key,JSONObject jsonObject){
        RedisAsyncCommands<String, String> async = redisConn.async();
        try {
            async.setex(key, 24 * 60 * 60,jsonObject.toJSONString());
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
